package com.epam.tcs.dao.hibernate;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

import com.epam.tcs.dao.hibernate.entities.Group;
import com.epam.tcs.dao.hibernate.entities.JournalLectureStatus;
import com.epam.tcs.dao.hibernate.entities.JournalPracticeStatus;
import com.epam.tcs.dao.hibernate.entities.Lecture;
import com.epam.tcs.dao.hibernate.entities.LectureStatus;
import com.epam.tcs.dao.hibernate.entities.Practice;
import com.epam.tcs.dao.hibernate.entities.PracticeStatus;
import com.epam.tcs.dao.hibernate.entities.Program;
import com.epam.tcs.dao.hibernate.entities.Student;
import com.epam.tcs.dao.hibernate.entities.Theme;
import com.epam.tcs.dao.hibernate.entities.ThemeItem;

public class ConnectionFactory {
	public static long timer = 0;
	public static SessionFactory sessionFactory = null;

	public static void initConnectionFactory() {
		Date dt = new Date();
		timer = dt.getTime();
		try {
			Configuration cfg = new Configuration()
					.addAnnotatedClass(Student.class)
					.addAnnotatedClass(Group.class)
					.addAnnotatedClass(Program.class)
					.addAnnotatedClass(Theme.class)
					.addAnnotatedClass(Lecture.class)
					.addAnnotatedClass(Practice.class)
					.addAnnotatedClass(LectureStatus.class)
					.addAnnotatedClass(PracticeStatus.class)
					.addAnnotatedClass(JournalLectureStatus.class)
					.addAnnotatedClass(JournalPracticeStatus.class)
					.addAnnotatedClass(ThemeItem.class).configure();
			sessionFactory = cfg.buildSessionFactory(new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry());
		} catch (MappingException e) {
			e.printStackTrace();
		} catch (HibernateException e) {
			e.printStackTrace();
			destroy();
		}
	}

	public static Session getOrInitSession() {
		try {
			Date curDate = new Date();
			long curTime = curDate.getTime();
			long tenminutes = 10 * 60 * 1000;
			if ((curTime - timer) > tenminutes) {
				destroy();
			} else {
				curDate = new Date();
				timer = curDate.getTime();
			}
			if (sessionFactory == null) {
				initConnectionFactory();
			}
			return sessionFactory.openSession();
		} catch (HibernateException e) {
			System.err.print(e);
			destroy();
			return null;
		}
	}

	public static void destroy() {
		timer = 0;
		try {
			if (sessionFactory != null) {
				sessionFactory.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		sessionFactory = null;
	}
}
